<?php

/**
 * Description of CalendarApiController
 *
 * @author Poh Nean
 */

class CalendarApiController extends PsController
{	
	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('Calendar.ManageAgency'),
					)), parent::accessRules());
	}
	
    /**
     * Updates a Cal Event. Handler for REST GET Method
     * Usage: GET api/contact
     */
    public function actionList($calendar_ids = null)
    {
		if (isset($calendar_ids)) {
			$_SESSION['calendarIds'] = explode(',', $calendar_ids);
		}
		
		if (isset($_SESSION['calendarIds'])) {
			$calendarIds = $_SESSION['calendarIds'];
		}
		
        $calendars = $this->loadCalendars();

        $data = array();
		
		$colors = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26);
		$arrLength = count($colors);
		
        if (!empty($calendars)) {
            foreach ($calendars as $i => $calendar) {
                $temp = array();
                $temp["id"] = $calendar->id;
                $temp["title"] = $calendar->user->name;
                $temp["desc"] = $calendar->displayname;
                $temp["color"] = $colors[($i % $arrLength)];
				if (isset($calendarIds)) {
					$temp["hidden"] = !in_array($calendar->id, $calendarIds);
				} else {
					$temp["hidden"] = false;
				}
                
                $data[] = $temp;
            }
        }

        // Send response
        $response = array();
        $response["success"] = true;
        $response["data"] = $data;

        print CJSON::encode($response);
    }


    public function getRequestVariables()
    {
        return json_decode(file_get_contents("php://input"));
    }
    
    public function loadCalendars() {
        $criteria = new CDbCriteria;
		$criteria->with = array('user');
		$criteria->together = true;
        $criteria->limit = 100;
		$criteria->order = 'user.name ASC';
		
        return CalCalendar::model()->ofCurrentAgency()->findAll($criteria);
    }
}

?>
